package com.lab.hive.udf;

import org.apache.hadoop.hive.ql.exec.UDAF;
import org.apache.hadoop.hive.ql.exec.UDAFEvaluator;
import org.apache.hadoop.io.IntWritable;

/**
 * 用户自定义聚合函数
 * 返回最大值
 * @author hadoop
 *
 */
public class Maximum extends UDAF {

  public static class MaximumIntUDAFEvaluator implements UDAFEvaluator {
    
    private IntWritable result;
    /** 
     * init函数类似于构造函数，用于UDAF的初始化 
     */  
    public void init() {
      System.err.printf("%s %s\n", hashCode(), "init");
      result = null;
    }
    /** 
     * iterate接收传入的参数，并进行内部的轮转。其返回类型为boolean 
     *  @param  value
     *  @return boolean
     */  
    public boolean iterate(IntWritable value) {
      System.err.printf("%s %s %s\n", hashCode(), "iterate", value);
      if (value == null) {
        return true;
      }
      if (result == null) {
        result = new IntWritable(value.get());
      } else {
        result.set(Math.max(result.get(), value.get()));
      }
      return true;
    }

    /** 
     * terminatePartial无参数，其为iterate函数遍历结束后，返回轮转数据， * 
     * terminatePartial类似于hadoop的Combiner * * 
     * @return 
     */  
    public IntWritable terminatePartial() {
      System.err.printf("%s %s\n", hashCode(), "terminatePartial");
      return result;
    }
    /** 
     * merge接收terminatePartial的返回结果，进行数据merge操作，其返回类型为boolean 
     */  
    public boolean merge(IntWritable other) {
      System.err.printf("%s %s %s\n", hashCode(), "merge", other);
      return iterate(other);
    }
    
    /** 
     * terminate返回最终的聚集函数结果 * * @return 
     */  
    public IntWritable terminate() {
      System.err.printf("%s %s\n", hashCode(), "terminate");
      return result;
    }
  }
}
